import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svprogresshud/flutter_svprogresshud.dart';
import 'package:goumao_app/Customs/gm_app_util.dart';
import 'package:goumao_app/Model/gm_vip_model.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

import '../Manager/gm_app_purchase_tool.dart';
import '../Manager/gm_user_manager.dart';
import '../Model/gm_login_user.dart';
import 'gm_touup_history.dart';

class GMMyQianbaoScreen extends StatefulWidget {
  const GMMyQianbaoScreen({super.key});
  @override
// ignore: library_private_types_in_public_api
  _GMMyQianbaoScreenState createState() => _GMMyQianbaoScreenState();
}

class _GMMyQianbaoScreenState extends State<GMMyQianbaoScreen> {
  late int index = 0;
  late Stream<List<PurchaseDetails>> _purchaseStream;

  List<GMVIPModel> proList = [];

  void _gmGetProList() async {
    String jsonString =
        await rootBundle.loadString('assets/mydata/gm_hy_data.json');
    Map<String, dynamic> jsonData = json.decode(jsonString);
    var data = GMVIPData.fromJson(jsonData);
    proList = data.coins!;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    _gmGetProList();
    _gmStartPurchase();
    GMInAppPurchaseTool.listenToPurchaseStream();
    GMInAppPurchaseTool.onPurchaseLoading = _onGmPurchaseLoading;
    GMInAppPurchaseTool.onPurchaseSuccess = _onGmPurchaseSuccess;
  }

  void _onGmPurchaseLoading() {
  }

  _gmRreshreBalance(int addedCoins) async {
    GMLoginUser user = GMUserManager().user!;
    user.coins = addedCoins + user.coins!;
    await GMUserManager().saveUser(user);
    setState(() {});
  }

  void _onGmPurchaseSuccess() {

    SVProgressHUD.dismiss();
    GMVIPModel data = proList[index];
    _gmRreshreBalance(int.parse(data.count!)); // Update the balance here
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('购买成功！获得${data.count!}金币'),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  _gmStartPurchase() async {
    if (!await GMInAppPurchaseTool.isAvailable()) {
      print('IAP is not available.');
      return;
    }

    _purchaseStream = GMInAppPurchaseTool.purchaseStream;
    _purchaseStream.listen((purchases) {
      for (var purchase in purchases) {
        print('Purchase Details: $purchase');
        if (purchase.status == PurchaseStatus.purchased) {
          GMInAppPurchaseTool.completePurchase(purchase);
        } else if (purchase.status == PurchaseStatus.error) {
          print('Purchase Error: ${purchase.error}');
          SVProgressHUD.dismiss();
        }
      }
    });
  }

  _gmToBuyProduct(String productId, int coins) async {
    // setState(() {
    //   isLoading = true;
    // });
    SVProgressHUD.show();
    try {
      print('Fetching product details for: $productId');
      var productDetails =
          await GMInAppPurchaseTool.getProductDetails([productId]);
      if (productDetails.isNotEmpty) {
        await GMInAppPurchaseTool.buyProduct(productDetails.first);
      } else {
        print('Product not found: $productId');
      }
    } catch (e) {
      print('An error occurred during purchase: $e');
    } finally {

    }
  }

  @override
  void dispose() {
    GMInAppPurchaseTool.cancelSubscription();
    super.dispose();
  }

  Widget _quanyiItemWidget(GMVIPModel data, int tag) {
    return InkWell(
      onTap: () {
        setState(() {
          index = tag;
        });
      },
      child: Container(
        height: 80,
        padding: const EdgeInsets.only(bottom: 16, left: 20, right: 20),
        child: Container(
          padding: const EdgeInsets.all(12),
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              color: const Color(0xffffffff),
              border: Border.all(
                  color: tag == index
                      ? const Color(0xff37A787)
                      : const Color(0xffffffff),
                  width: 1.0)),
          child: Row(
            children: [
              Image.asset(
                "assets/images/gm_jb_icon@2x.png",
                width: 28,
              ),
              const SizedBox(
                width: 12,
              ),
              Text(
                data.count!,
                style: const TextStyle(
                    color: Color(0xff333333),
                    fontSize: 14,
                    fontWeight: FontWeight.w800),
              ),
              const Spacer(),
              Text(
                'HK${data.price1!.toString()}',
                style: const TextStyle(
                    color: GMAppUtil.kAppThemColor,
                    fontSize: 16,
                    fontWeight: FontWeight.w700),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _gmVIPTopWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: const EdgeInsets.fromLTRB(20, 24, 20, 0),
          height: 106,
          color: const Color(0xff13392F),
          child: Container(
            padding: const EdgeInsets.fromLTRB(20, 12, 20, 12),
            decoration: const BoxDecoration(
                image: DecorationImage(
                    image: AssetImage("assets/images/gm_vip_top_bg@2x.png"),
                    fit: BoxFit.cover)),
            child: Row(
              // crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Text(
                      "金币余额",
                      style: TextStyle(
                          color: Color(0xffffffff),
                          fontSize: 14,
                          fontWeight: FontWeight.w900),
                    ),
                    Row(
                      children: [
                        Image.asset(
                          "assets/images/gm_jb_icon@2x.png",
                          width: 24,
                        ),
                        const SizedBox(
                          width: 10,
                        ),
                        Text(
                          GMUserManager().user!.coins == null
                              ? "0"
                              : GMUserManager().user!.coins.toString(),
                          style: const TextStyle(
                              color: Color(0xffffffff),
                              fontSize: 28,
                              fontWeight: FontWeight.w900),
                        )
                      ],
                    )
                  ],
                ),
                InkWell(
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => const GMTouupHistoryScreen(),
                      ),
                    );
                  },
                  child: Container(
                    height: 28,
                    width: 72,
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(14),
                        color: const Color(0xffffffff)),
                    alignment: Alignment.center,
                    child: const Text(
                      "金币记录",
                      style: TextStyle(
                          color: Color(0xff1a1a1a),
                          fontSize: 12,
                          fontWeight: FontWeight.w600),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
        const SizedBox(
          height: 20,
        ),
        Container(
          padding: const EdgeInsets.fromLTRB(20, 0, 20, 16),
          child: const Column(
            children: [
              Text(
                "选择充值金额",
                style: TextStyle(
                    color: Color(0xff333333),
                    fontSize: 16,
                    fontWeight: FontWeight.w800),
              ),
            ],
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff8f8f8),
      appBar: AppBar(
        elevation: 0,
        title: const Text(
          "我的钱包",
          style: TextStyle(
              color: Colors.white, fontWeight: FontWeight.w900, fontSize: 16),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          color: Colors.white, // 修改返回按钮颜色
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        backgroundColor: const Color(0xff13392F),
      ),
      body: Column(
        children: [
          Expanded(
            child: CustomScrollView(
              slivers: [
                SliverToBoxAdapter(child: _gmVIPTopWidget()),
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      return _quanyiItemWidget(proList[index], index);
                    },
                    childCount: proList.length,
                  ),
                )
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.fromLTRB(
                20, 20, 20, 20 + ScreenUtil().bottomBarHeight),
            child: InkWell(
              onTap: () {
                GMVIPModel data = proList[index];
                _gmToBuyProduct(data.pid!, int.parse(data.count!));
              },
              child: Container(
                alignment: Alignment.center,
                height: 50,
                decoration: BoxDecoration(
                    color: const Color(0xff37A787),
                    borderRadius: BorderRadius.circular(25)),
                child: const Text(
                  "立即充值",
                  style: TextStyle(
                      color: Color(0xffffffff),
                      fontSize: 15,
                      fontWeight: FontWeight.w600),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
